/*
appTokenAuth.js
*/

var apiStatus = require('../apiStatus');
var dbLayer = require('./dataAccess');
var security = require('./security');

module.exports = (function(){
	var isUnless = function(ctx) {
		var url = ctx.request.url;
		var less = [
			"/message/notify",
			"/tools"
		]
		return less.some(function (n) {
			return url.indexOf(n) > -1;
		});
	}
	return async function (ctx,next){
		if (isUnless(ctx)){
			await next();
			return;
		}

		var token = ctx.request.header['app-token'];

		if (!token){
			ctx.body = {apiStatus: apiStatus.appTokenRequired};
			return;
		}
		var parts = token.split('|');
		if (parts.length != 3){
			ctx.body = {apiStatus: apiStatus.appTokenInvalid};
			return;
		}

		var appKey = parts[0];
		var ts = parts[1];
		var digt = parts[2];

		var tsNow = Math.floor(new Date().getTime() / 1000);
		if ((tsNow - ts) > 5 * 60 ) {
			//ctx.body = {apiStatus: apiStatus.appTokenTimeStampInvalid};
			//return;
		}
		console.log("appKey:" + appKey);
		try{
			var results = await dbLayer.sys.query('SELECT * FROM apps WHERE appKey = ?',[appKey]);
			var appInfo = results[0];
			if (!appInfo){
				ctx.body = {apiStatus: apiStatus.appTokenInvalid};
				return;
			}

			var sToken = appKey + '|' +  ts + '|' + appInfo.appSecret;
			var sDigt = security.md5(sToken);
			if (sDigt != digt){
				ctx.body = {apiStatus: apiStatus.appTokenInvalid};
				return;
			}
			ctx.appTokenAuthenticated = true;
			ctx.appInfo = appInfo;
		}catch(e){
			 ctx.body = {apiStatus: apiStatus.appTokenInvalid};
			 return;
		}
		await next();
	};

})();
